<?php

/**
 * Aurorum - Open source digital signage
 *
 * @link http://digitalsignage.tk
 * @license http://www.gnu.org/licenses/gpl-3.0.html GPL v3 or later
 *
 * @category Aurorum
 * @package Aurorum
 */

/**
 * This class provides access to data layer.
 *
 * @package Aurorum
 * @subpackage Models
 */

class ADS_CommandModel extends ADS_DefaultModel {

    public function countCommands() {
        return dibi::fetch('
          SELECT
            COUNT(*) as cnt
          FROM
            [:wp:ads_commands]
          %if', (bool)$this->useFilter, 'WHERE %and', $this->filter
        )->cnt;
    }
    
    public function getCommands() {
        return dibi::fetchAll('
          SELECT            
            *
          FROM
            [:wp:ads_commands] AS t1
           %if', (bool)$this->useFilter, 'WHERE %and', $this->filter, '%end',
          '%if', (bool)$this->useOrderBy, 'ORDER BY %by', $this->orderBy, '%end',
          '%if', (bool)$this->useLimit, '%lmt %ofs', $this->limit, $this->offset
        );
    }
     
    public function getCommand($commandId) {
        if(!is_int($commandId)){
            throw new InvalidArgumentException(sprintf('Wrong parameters for method %s.',__METHOD__));
        }
        return dibi::fetch('
          SELECT            
            *
          FROM
            [:wp:ads_commands] AS t1
          WHERE
            commandId = %i
        ', $commandId);
    }
    
    public function addCommand($command){
        if(!is_array($command)){
            throw new InvalidArgumentException(sprintf('Wrong parameters for method %.',__METHOD__));
        }
        dibi::query('INSERT INTO [:wp:ads_commands]', $command);
    }
    
    public function editCommand($commandId, $command){
        if(!is_array($command) || !is_int($commandId)){
            throw new InvalidArgumentException(sprintf('Wrong parameters for method %.',__METHOD__));
        }

        dibi::query('UPDATE [:wp:ads_commands] SET', $command, 'WHERE commandId = %i', $commandId);
    }
    
    public function removeCommand($commandId){
        if(!is_int($commandId)){
            throw new InvalidArgumentException(sprintf('Wrong parameters for method %.',__METHOD__));
        }
        $command = $this->getCommand($commandId);
        //update positions
        dibi::query('DELETE FROM [:wp:ads_commands] WHERE commandId = %i LIMIT 1', $commandId);
    }

}
